<template>
  <div class="index-container">
    <div class="top" :class="props.index%2 == 0 ? 'left' : 'right'"></div>
    <!-- <div v-else class="top" :class="index == 0 ? 'left' : index == 2 ? 'right' : 'sp'"></div> -->
    <div class="index-title">
      <div class="responsible-company font-bold" v-if="props.quota.industryName == '国家重点管控资源'">
        <span>稀土价格</span>
      </div>
      <div class="responsible-company" v-else>
        <span>责任单位：</span><span>{{ props.quota.department || '--'}}</span>
      </div>
      <div @click="favBtn">
        <img v-if="star == 1" class="fav-btn" src="@/assets/icon/xing-checked.png" />
        <img v-else class="fav-btn" src="@/assets/icon/xing.png" />
      </div>
    </div>
    <div style="width: 100%" v-if="threshold !== null">
      <div class="error">{{ threshold }}</div>
    </div>
    <div class="btn-contact" v-if="props.quota.industryName != '国家重点管控资源'">
      <img src="@/assets/keyIndicator/icon-contact.png" alt />
      <span @click="showPickerClick">联系责任人</span>
    </div>
    <div>
      <div v-if="copyAnomalyTotal.length > 0" class="area-title">
        <div style="width: 100%; padding-left: 0" class="area-title dashed">
          <div class="icon"></div>
          {{titleText('区域分布')}}
        </div>
      </div>
      <div class="anomaly-echarts">
        <div v-if="copyAnomalyTotal.length > 0" class="echartClass">
          <div
            v-for="item in !isExpand ? copyAnomalyTotal : mapEcharts"
            :key="item"
            class="echarts-box"
          >
            <div class="echarts-title">{{ item.name }}</div>
            <div class="echarts-lint">
              <div class="echarts-left">
                <div class="box">
                  <div class="echarts-pad" :style="{ width: percent(item.value) }" />
                </div>
              </div>
              <div class="echarts-num">
                <div>{{ item.value }}</div>
                <!-- <div class="numlin" />
                <div>{{ item.rata }}</div> -->
              </div>
            </div>
          </div>
        </div>
        <div v-if="mapEcharts && mapEcharts.length > 6" class="more">
          <img @click="moreClick" v-if="!isExpand" src="@/assets/icon/more-down.png" />
          <img @click="moreClick" v-else src="@/assets/icon/more-up.png" />
        </div>
      </div>
      <div v-if="hasTrend()" class="trend-change">
        <div class="area-title dashed">
          <div class="icon"></div>
          趋势变化
        </div>
        <div class="trend-echarts-unit">
          {{ props.detail.pieOutPutEntity.lineBarVo.type }}<span v-if="props.detail.pieOutPutEntity.lineBarVo.unit">/</span>{{ props.detail.pieOutPutEntity.lineBarVo.unit }}
        </div>
        <div
          :id="`trend-echarts${props.quota.id}`"
          style="width: 100%; height: 50vw; margin-bottom: 1vw"
        />
      </div>
      <div v-if="hasStructure()" class="trend-change">
        <div class="area-title dashed">
          <div class="icon"></div>
          {{titleText("结构分析")}}
        </div>
        <!-- 需求变更为柱状图 -->
        <div
          v-show="props.detail.pieOutPutEntity.echartLinesBarEntity"
          :id="`structure-echarts-bar${props.quota.id}`"
          class="chart-pie"
        />
        <!-- 环形图 -->
        <div class="pie-content" v-show="hasPieStructure()" :class="{'littleWrap':pieEcharts.length<4}">
          <div
            :id="`structure-echarts${props.quota.id}`"
            class="chart-pie"
            :style="{ height: pieChartHeight + 'vw' }"
          />
          <div class="legend-content legend-right">
            <div class="item" v-for="(item,index) in pieLegendR" :key="'R'+index">
              <p><span class="icon" :style="{borderColor: item.color}"></span><span class="name ellipsis">{{item.name}}</span><span class="tip">{{item.name}}</span></p>
              <p class="ellipsis number" :style="{color: item.color}"><span class="value">{{item.rate}}</span> <span class="rate">{{item.value}}{{item.unit}}</span></p>
            </div>
          </div>
          <div class="legend-content legend-left" v-show="pieLegendL.length">
            <div class="list" :id="`pie-legend${props.quota.id}`">
              <div class="item" v-for="(item,index) in pieLegendLThree" :key="'L'+index">
                <p class="reseve"><span class="icon" :style="{borderColor: item.color}"></span><span class="name ellipsis">{{item.name}}</span><span class="tip">{{item.name}}</span></p>
                <p class="ellipsis number" :style="{color: item.color}"><span class="value">{{item.rate}}</span> <span class="rate">{{item.value}}{{item.unit}}</span></p>
              </div>
            </div>
            <div class="flex-center" v-if="pieLegendL.length>3">
              <van-icon class="legend-up" :class="{'disable':pieLegendCurrentPage==1}" name="play" size="24px" @click="handleLegendPage('prev')"/>
              <span>{{pieLegendCurrentPage}}/{{pieLegendPage}}</span>
              <van-icon class="legend-down" :class="{'disable':pieLegendCurrentPage==pieLegendPage}" name="play" size="24px" @click="handleLegendPage('next')"/>
            </div>
          </div>
        </div>
      </div>

      <!-- 国家资源管控 -->
      <div class="trend-change" v-if="hasPreDict()">
        <div class="area-title dashed">
          <div class="icon"></div>
          变化趋势
        </div>
        <div
          :id="`predict-echarts${props.quota.id}`"
          style="width: 100%; height: 45vw;"
        />
      </div>
      <div class="trend-change" v-if="props.quota?.recommended">
        <div class="area-title dashed">
          <img class="icon-tuijian" src="@/assets/icon/icon-tuijian.png" alt="">
          预测推荐
        </div>
        <div class="tuijian-list">
          <div class="flex-center" v-for="(item,index) in props.quota.recommended" :key="item.name">
            <div class="flex-start">
              <p class="line" :style="{'borderTopColor':filterBorderColor(item.name)}"></p>
              <p>{{item.name}}</p>
            </div>
            <div class="icon-star flex-between">
              <span v-for="star in 5" :key="star" :class="{'active':index<star}"></span>
            </div>
          </div>
        </div>
        <p style="height:2.6667vw"></p>
      </div>
      <div class="trend-change city-compare" v-if="cityTableData.length">
        <div class="area-title dashed">
          <div class="icon"></div>
          城市比较
        </div>
        <table>
          <tr>
            <th>排名</th>
            <th>城市</th>
            <th>数值 <span v-if="cityTableData[0]&&cityTableData[0].unit">({{cityTableData[0].unit}})</span></th>
          </tr>
          <tr v-for="td in !isCompaeExpand ? cityTableFiveData : cityTableData" :key="td.rank">
            <td>{{td.rank}}</td>
            <td>{{td.cityName}}</td>
            <td>{{td.value}}</td>
          </tr>
        </table>
        <div class="line"></div>
        <div v-if="cityTableData && cityTableData.length > 6" class="more">
          <img @click="moreClick('cityCompare')" v-if="!isCompaeExpand" src="@/assets/icon/more-down.png" />
          <img @click="moreClick('cityCompare')" v-else src="@/assets/icon/more-up.png" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { showToast } from 'vant'
import * as echarts from 'echarts'
import { computed, ref, reactive, toRefs, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useQuotaStore } from '@/store'

import { IndexDetailLineChart, IndexDetailSectorBarChart, IndexDetailSectorChart, IndexDetailPredictLineChart, colorList } from "@/views/home/components/IndexEChart.js"

import FavServe from '@/api/fav'
import QuotaServe from '@/api/quota'
import { useContactStore } from '@/store'
import { storeToRefs } from 'pinia'

const contactStore = useContactStore()
const { anomalyIndex } = storeToRefs(contactStore)
const showPickerClick = () =>{
  if(props.quota.threshold){
    anomalyIndex.value = props.quota.quotaName
  }else{
    anomalyIndex.value = null
  }
  contactStore.fetchUserDetail(props.detail.personLiable)
}
const quotaStore = useQuotaStore()
const props = defineProps({
  quota: {
    type: Object,
    default: null
  },
  detail: {
    type: Object,
    default: null
  },
  index: {
    type: Number,
    default: 0
  },
  type: {
    type: Number,
    default: 0
  },
  threshold: {
    type: String,
    default: null
  }
})
// 根据图例数量计算饼图高度
const pieChartHeight = ref((100 / document.documentElement.clientWidth) * 171)
watch(
  () => pieChartHeight.value,
  () => {
    nextTick(() => {
      structureEcharts?.resize()
    })
  }
)
// 判断是否有数据
const hasLineBarVo = computed(() => {
  return props.detail.pieOutPutEntity.hasOwnProperty('lineBarVo')
})
const isExpand = ref(false)
const isCompaeExpand = ref(false)
const hasTrend = () => {
  if (props.detail.pieOutPutEntity == null) {
    return false
  } else if (props.detail.pieOutPutEntity.lineBarVo == null) {
    return false
  } else if (props.detail.pieOutPutEntity.lineBarVo.series.length == 0) {
    return false
  } else {
    return true
  }
}

const lineColors = [
  { name: '梯度回归', color: '#8095FF' },
  { name: '决策树', color: '#01BE76' },
  { name: 'XGBoost', color: '#EB9100' },
  { name: '循环神经网络', color: '#E34732' }
]

const hasPreDict = () => {
  if(props.detail.predictEntity){
      return true
  } else {
    return false
  }
}

const filterBorderColor = (name) => {
  const colorIndex = lineColors.findIndex(c => c.name == name)
  return lineColors[colorIndex].color
}
const hasStructure = () => {
  if (props.detail.pieOutPutEntity == null) {
    return false
  } else if (props.detail.pieOutPutEntity.echartPieEntity == null && props.detail.pieOutPutEntity.echartLinesBarEntity == null) {
    return false
  } else if (props.detail.pieOutPutEntity.echartPieEntity?.series[0]?.data.length == 0 && props.detail.pieOutPutEntity.echartLinesBarEntity == null) {
    return false
  } else {
    return true
  }
}
const hasPieStructure = () => {
  if (props.detail.pieOutPutEntity.echartPieEntity == null || props.detail.pieOutPutEntity.echartPieEntity?.series[0]?.data.length == 0) {
    return false
  }else{
    return true
  }
}
const moreClick = (type) => {
  if(type == 'cityCompare'){  //城市比较
    isCompaeExpand.value = !isCompaeExpand.value
  }else{
    isExpand.value = !isExpand.value
  }
}
const getMap = ref([])
const star = ref(props.quota.collectFlag)
const mapEcharts = ref([])
const lineEcharts = ref([])
const lineEchartsServe = ref([])
const pieEcharts = ref([])
const pieLegendL = ref([])
const pieLegendLThree = ref([])
const pieLegendR = ref([])
const pieLegendPage = ref(1)
const pieLegendCurrentPage = ref(1)
// 拷贝前五个
let copyAnomalyTotal = reactive([])
let trendEcharts, structureEcharts

const moreBtn = ref(false)
const btnShow = ref(true)

const emit = defineEmits(['Favrefresh'])
const favBtn = async () => {
  let quotaId = props.quota?.id || props.quota?.quotaId
  if (star.value == 1) {
    star.value = 0
  } else {
    star.value = 1
  }
  try {
    await FavServe.selCollectById({
      collect: quotaId,
      flag: props.quota.collectFlag || 0
    }).then(() => {
      showToast(props.quota.collectFlag==1?'取消收藏成功':'收藏成功')
      emit('Favrefresh', star.value)
      quotaStore.fetchFavQuotaList()
    })
  } catch (error) {
    console.log(error)
  }
}
onMounted(() => {
  // 获取区域数据
  const current = (props.detail?.mapOutPutEntity?.cgjybzIndustryDataHotmap || []).sort(function (
    a,
    b
  ) {
    return b.value - a.value
  })
  getMap.value = (current || []).map(item => {
    //  const sum += item.value
    let sum = 0
    for (let i = 0; i < current.length; i++) {
      sum += Number(current[i].value)
    }
    const single = {
      name: item.district,
      value: item.value,
      rata: `${((item.value * 100) / sum).toFixed(2)}% `
    }
    return mapEcharts.value.push(single)
  })
  if (mapEcharts.value.length >= 5) {
    copyAnomalyTotal = mapEcharts.value.slice(0, 5)
  } else {
    copyAnomalyTotal = mapEcharts.value
  }
  // 获取折线图数据
  lineEcharts.value = props.detail?.pieOutPutEntity?.lineBarVo?.xaxis
  lineEchartsServe.value = props.detail?.pieOutPutEntity?.lineBarVo?.series
  // pieEcharts.value.sort(function (a, b) {
  //   return b.value - a.value
  // })
  // 折线图
  if (hasTrend()) {
    IndexDetailLineChart(`trend-echarts${props.quota.id}`, props.detail.pieOutPutEntity.lineBarVo)
  }
  // 饼图
  if (hasStructure()) {
    if(props.detail.pieOutPutEntity.echartLinesBarEntity){
      IndexDetailSectorBarChart(`structure-echarts-bar${props.quota.id}`, props.detail.pieOutPutEntity.echartLinesBarEntity)
    }
    if(props.detail.pieOutPutEntity.echartPieEntity){
      // 获取饼图数据
      pieEcharts.value = props.detail?.pieOutPutEntity?.echartPieEntity?.series[0]?.data?.length
        ? props.detail.pieOutPutEntity?.echartPieEntity?.series[0]?.data
        : []
      pieEcharts.value.forEach((ele,index)=>{
        ele.indexN = index;
        ele.color = colorList[index].gradientStart
      })
      let dataLen = pieEcharts.value.length
      pieLegendR.value = pieEcharts.value.slice(0, 3)
      pieLegendL.value = pieEcharts.value.slice(3, dataLen)
      pieLegendLThree.value = pieLegendL.value.slice(0, 3)
      pieLegendPage.value = pieLegendL.value.length?Math.ceil(pieLegendL.value.length/3):1
      const width = document.documentElement.clientWidth
      const height = Math.max(151, (pieEcharts.value.length>6?6:pieEcharts.value.length) * 29)
      // 文字超过14字时会换行，换行会增加高度，所以最终高度要加上换行高度
      const wrapHeight = pieEcharts.value.filter(item => item.name.length > 14).length * 8
      const wrapWidth = pieEcharts.value.length<4?60: 120;
      pieChartHeight.value = (100 / width) * (height + wrapHeight)
      nextTick(()=>{
        IndexDetailSectorChart(`structure-echarts${props.quota.id}`, pieEcharts.value)
      })
    }
  }
  // 变化趋势预测折线图
  if(hasPreDict()){
    IndexDetailPredictLineChart(`predict-echarts${props.quota.id}`, props.detail.predictEntity, lineColors)
  }
  window.onresize = function () {
    // 自适应大小
    myChart.resize()
  }
  //获取城市比较
  getCityCompareData()
})

onUnmounted(() => {
  if (trendEcharts) {
    trendEcharts.dispose()
    trendEcharts = null
  }
  if (structureEcharts) {
    structureEcharts.dispose()
    structureEcharts = null
  }
})
//环形图分页
const handleLegendPage = (type) => {
  let doc = document.getElementById(`pie-legend${props.quota.id}`)
  if(type=='next'){
    if(pieLegendCurrentPage.value == pieLegendPage.value){
      return
    }
    // doc.scrollTop = 130*pieLegendCurrentPage.value;
    pieLegendLThree.value = pieLegendL.value.slice(pieLegendCurrentPage.value*3,pieLegendCurrentPage.value*3+3)
    pieLegendCurrentPage.value++
  } else {
    if(pieLegendCurrentPage.value == 1){
      return
    }
    pieLegendCurrentPage.value--
    // doc.scrollTop = 130*(pieLegendCurrentPage.value-1);
    
    pieLegendLThree.value = pieLegendL.value.slice((pieLegendCurrentPage.value-1)*3,(pieLegendCurrentPage.value-1)*3+3)
  }
}

//计算进度条宽度
const percent = (value) => {
  let v = value
  let maxVal = Math.max.apply(Math,mapEcharts.value.map(item => { return item.value }))
  let minVal = Math.min.apply(Math,mapEcharts.value.map(item => { return item.value }))

  if(minVal < 0){
    v = Number(value) + Math.abs(minVal)
    maxVal = maxVal + Math.abs(minVal)
  }
  // if (value < 0){
  //   v = 0;
  // }
  if (value > maxVal){
    v = maxVal;
  }
  return (v / maxVal) * 100  + '%';
}

//标题加单位
const titleText = (val) => {
  let unitText = props.quota.unit?'（' + props.quota.unit + '）':''
  return val + unitText
}

//城市表比较
const cityTableData = ref([])
const cityTableFiveData = ref([])
const getCityCompareData = () => {
  let quotaId = props.quota?.id || props.quota?.quotaId
  QuotaServe.getCitiesCompare(quotaId).then((res) => {
    cityTableData.value = res.data
    if (res.data.length >= 5) {
      cityTableFiveData.value = res.data.slice(0, 5)
    }
  })
}
</script>
<style scoped lang="less">
.index-container {
  width: 330px;
  background-color: #f2f6fa;
  border-radius: 8px;
  margin-top: 10px;
  position: relative;
  .error {
    font-size: 12px;
    color: #e83a48;
    padding: 0 12px 8px;
  }
  .top {
    width: 100%;
    height: 5px;
    position: absolute;
    top: -4px;
    right: 0;
  }
  .left {
    background: url(@/assets/home/blue-road-left.png) no-repeat;
    background-size: 100% 100%;
  }
  .right {
    background: url(@/assets/home/blue-road-right.png) no-repeat;
    background-size: 100% 100%;
  }
  .sp {
    background: url(@/assets/home/blue-road-left.png) no-repeat;
    right: 4%;
  }
  .index-title {
    padding: 0 10px;
    position: relative;
    .fav-btn {
      position: absolute;
      top: 0;
      right: 12px;
      width: 20px;
    }
  }
}
.responsible-company {
  height: 16.03px;
  font-weight: 500;
  color: #212121;
  font-size: 11.54px;
  padding: 12px 0;
  &.font-bold{
    font-size: 15px;
    font-weight: 900;
  }
}
.trend-change {
  width: 310px;
  border-radius: 7.69px;
  padding: 0 10px;
  position: relative;

  .trend-echarts-unit {
    position: absolute;
    height: 14.42px;
    font-family: 'PingFang SC';
    font-weight: 600;
    color: #666666;
    font-size: 10.26px;
    top: 44px;

    left: 15px;
  }
  .chart-pie {
    width: 100%;
    height: 150.99px;
  }
}
.anomaly-echarts {
  width: 100%;
  border-radius: 8px;
  position: relative;
  .echarts-title {
    padding: 10px 8px 6px 0;
    color: #333333;
    font-size: 12px;
    letter-spacing: 1px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    position: relative;
    top: -3px;
    min-width: 68px;
    max-width: 68px;
  }

  .echartClass {
    width: 310px;
    border-radius: 8px 8px 0 0;
    margin: auto;
    overflow: hidden;
    padding-bottom: 15px;

    .echarts-box {
      display: flex;
      height: 33px;

      .echarts-lint {
        display: flex;
        align-items: center;
        flex-grow: 1;
        .echarts-left {
          width: 165px;
          height: 12px;
          .box {
            width: 100%;
            height: 100%;
            border-radius: 0 12px 12px 0;
            background: rgba(46, 138, 230, 0.1);
            display: flex;
            align-items: center;
            .echarts-pad {
              height: 50%;
              border-radius: 0 12px 12px 0;
              // width: 66%;
              background: linear-gradient(90deg, #66bfff 0%, #2681ff 100%);
            }
          }
        }

        .echarts-num {
          display: flex;
          align-items: center;
          margin-left: 7px;

          .numlin {
            width: 1px;
            transform: scaleX(0.5);
            height: 8px;
            background: #000;
            margin: 0 5px;
          }
        }
      }
    }

    .echartsNull {
      width: 100px;
      height: 92px;
      background: url(@/assets/no_data.png) no-repeat;
      background-size: cover;
    }
  }

  .echartsListNull {
    width: 329px;
    height: 224px;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 100px;
      height: 92px;
    }
  }

}
.more {
  width: 310px;
  height: 15px;
  position: absolute;
  bottom: -10px;
  display: flex;
  justify-content: center;
  z-index: 99;
  img {
    width: 20px;
    height: 15px;
  }
}
.area-title {
  height: 5.7253vw;
  color: #212121;
  font-size: 14px;
  font-weight: bold;
  padding-left: 2.1333vw;
  display: flex;
  align-items: center;
  padding-top: 13px;
  margin-bottom: 10px;
}
.icon {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #3d76ff;
  margin-right: 6px;
}
.dashed {
  border-top: 2px dashed rgba(61, 118, 204, 0.2);
  padding-left: 0 !important;
}
.icon-tuijian{
  width: 20px;
  height: 20px;
  margin-right: 8px;
}
.tuijian-list{
  border-radius: 4px;
  background: #FFFFFFB2;
  padding: 10px 0;
  color: #212121;
  font-size: 12px;

  >div{
    height: 24px;
  }
  .line{
    border-top: 1.5px dashed #8095FF;
    width: 22px;
    height: 1px;
    margin-right: 8px;
    &+p{
      min-width: 75px;
    }
  }
  .icon-star{
    width: 63px;
    margin-left: 8px;
    flex-direction: row-reverse;
    span{
      display: block;
      width: 11.5px;
      height: 11.5px;
      background: url("@/assets/icon/icon-star.png") no-repeat center center;
      background-size: 100% 100%;
      &.active{
        background-image: url("@/assets/icon/icon-star-active.png");
      }
    }
  }
}
.city-compare{
  margin-top: 10px;
  padding-bottom: 15px;
  table{
    width: 100%;
    text-align: center;
    th{
      color: #000;
      line-height: 30px;
    }
    td{
      color: #666;
      padding: 4px 0;
      font-size: 12px;
    }
  }
  .line{
    border-bottom: 2px dashed rgba(61, 118, 204, 0.2);
    margin-top: 10px;
  }
  .more{
    bottom: 7px;
  }
}
.pie-content{
  position: relative;
}
.littleWrap{
  width: 55%;
  .legend-content.legend-right{
    right: -120px;
    width: 130px;
  }
}
.legend-content{
  position: absolute;
  top: 0;
  color: #212121;
  font-size: 13px;
  width: 100px;
  &.legend-left{
    left: 0;
    .list{
      height: 130px;
      overflow: hidden;
    }
    .item{
      text-align: right;
      .reseve{
        display: flex;
        flex-direction: row-reverse;
        .icon{
          margin: 2px 0 0 5px;
        }
      }
    }
  }
  &.legend-right{
    right: 0;
  }
  .icon{
    display: inline-block;
    width: 5px;
    height: 5px;
    border: 2.5px solid #fff;
    background: #fff;
  }
  .value{
    margin-right: 3px;
  }
  .value,.rate{
    font-size: 14px;
    line-height: 24px;
  }
  .item{
    margin: 5px 0;
    position: relative;
  }
  .tip{
    display: none;
    background: rgba(0,0,0,0.6);
    padding: 5px 15px;
    color: #fff;
    font-size: 12px;
    border-radius: 5px;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translate(-50%,0);
    width: max-content;
  }
  .legend-up{
    transform: rotate(-90deg);
    margin: 0 3px;
  }
  .legend-down{
    transform: rotate(90deg);
    margin: -5px 0 0 3px;
  }
  .disable{
    color: #999;
  }
  .name:hover+.tip,.number:hover+.tip{
    display: block;
  }
}
.btn-contact{
  display: flex;
  align-items: center;
  padding: 0 12px 8px;
  color: #3D76CC;
  font-size: 13px;
  img{
    width: 15px;
    height: 15px;
    margin-right: 3px;
  }
}
</style>
